package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.File;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.MessageUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.mail.EmailUtils;
import com.ruoyi.system.domain.SysMessage;
import com.ruoyi.system.domain.SysReply;
import com.ruoyi.system.domain.SysUserOnline;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.relation.Role;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import static com.ruoyi.common.utils.SecurityUtils.isAdmin;
import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * 留言 服务层实现
 *
 * @author ruoyi
 */
@Service
public class SysMessageServiceImpl implements ISysMessageService
{
    @Autowired
    private SysMessageMapper messageMapper;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private SysReplyMapper sysReplyMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private EmailUtils emailUtils;

    @Autowired
    private MessageUtil messageUtil;

    /**
     * 查询留言信息
     *
     * @param id 留言ID
     * @return 留言信息
     */
    @Override
    public SysMessage selectMessageById(Long id)
    {
        SysMessage sysMessage = messageMapper.selectMessageById(id);
        try {
            if(sysMessage != null){
                String messageType = sysMessage.getMessageType();
                //留言类型
                String messageTypeName = sysDictDataService.selectDictLabel("sys_message_type",messageType);
                sysMessage.setMessageTypeName(messageTypeName);

                String messageStatus = sysMessage.getMessageStatus();
                //留言状态
                String messageStatusName = sysDictDataService.selectDictLabel("sys_message_status",messageStatus);
                sysMessage.setMessageStatusName(messageStatusName);

                //根据messgaeType获取 name
                //先获取留言表的文件集合
                File messageFile = new File();
                messageFile.setDelFlag("0");
                messageFile.setMessageId(id);
                List<File> messageFileList = fileMapper.selectFileList(messageFile);
                if(CollectionUtil.isNotEmpty(messageFileList)){
                    sysMessage.setMessageFileList(messageFileList);
                }

                //获取留言集合
                SysReply query = new SysReply();
                query.setDelFlag("0");
                query.setMessageId(id);
                List<SysReply> sysReplyList = sysReplyMapper.selectReplyList(query);
                if(CollectionUtil.isNotEmpty(sysReplyList)){
                    sysReplyList.stream().forEach(sysReply -> {
                        //获取回复的文件集合
                        Long replyId = sysReply.getId();//回复id
                        File replyFile = new File();
                        replyFile.setDelFlag("0");
                        replyFile.setReplyId(replyId);
                        List<File> replyFileList = fileMapper.selectFileList(replyFile);
                        if(CollectionUtil.isNotEmpty(replyFileList)){
                            sysReply.setReplyFileList(replyFileList);
                        }
                    });

                    sysMessage.setSysReplyList(sysReplyList);
                }

                //获取留言人信息
                String createBy = sysMessage.getCreateBy();
                if(StringUtils.isNotEmpty(createBy)){
                    Long userId = Long.parseLong(createBy);
                    SysUser sysUser = sysUserMapper.selectUserById(userId);
                    if(sysUser != null){
                        sysMessage.setSysUser(sysUser);
                    }
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return sysMessage;
    }

    /**
     * 查询留言列表
     *
     * @param message 留言信息
     * @return 留言集合
     */
    @Override
    public List<SysMessage> selectMessageList(SysMessage message)
    {
        LoginUser loginUser = getLoginUser();//获取当前登录信息
        if(loginUser == null){
            return new ArrayList<>();
        }
        SysUser sysUser = loginUser.getUser();
       //根据userId 获取irRegister
        if(sysUser != null){
            //是否注册 1已注册，0未注册（手机与邮箱注册的用户都是已注册，    后台新增的用户都为未注册）
            String isRegister = sysUser.getIsRegister() == null? "0":sysUser.getIsRegister() ;//是否注册 1已注册，0未注册
            if(StringUtils.isNotEmpty(isRegister) && isRegister.equals("1")){
                message.setCreateBy(String.valueOf(sysUser.getUserId()));
            }
        }
        return messageMapper.selectMessageList(message);
    }

    /**
     * 新增留言
     *
     * @param message 留言信息
     * @return 结果
     */
    @Override
    public int insertMessage(SysMessage message)
    {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        Date date = new Date();
        message.setMessageTime(date);
        int n = messageMapper.insertMessage(message);
        String fileId = message.getFileId();
        if(StringUtils.isNotEmpty(fileId)){
            String newFileId = StringUtils.strip(fileId,"[]");
            if(StringUtils.isNotEmpty(newFileId)){
                String[] fileIds = newFileId.split(",");
                for(int i = 0 ;i < fileIds.length; i++){
                    setMessageFileId(message.getId(),Integer.parseInt(fileIds[i]));
                }
            }
        }
        //找到 CEO信箱管理员角色中的所有用户
        List<SysUser> userList = getCEOList("CEO信箱管理员");
        if(CollectionUtil.isNotEmpty(userList)){
            userList.stream().forEach(sysUser -> {
                if(sysUser != null){
                    String email = sysUser.getEmail();
                    if(StringUtils.isNotEmpty(email)){
                        Map valueMap = new HashMap();
                        valueMap.put("to",email);
                        valueMap.put("title",message.getMessageTitle());
                        String content = "以下数据已经更新，请及时查看和处理" +
                                "<br>留言标题：" + message.getMessageTitle() +
                                "<br>更新时间：" + simpleDateFormat.format(date) +
                                "<br>留言内容："+ message.getMessageContent();
                        valueMap.put("content","${s}");
                        valueMap.put("s",content);
                        String thymeleaf="";
                        emailUtils.sendMail(valueMap,thymeleaf);
                    }
                }
            });
        }
        return n;
    }

    /**
     * 修改留言
     *
     * @param message 留言信息
     * @return 结果
     */
    @Override
    public int updateMessage(SysMessage message)
    {
        String fileId = message.getFileId();
        if(StringUtils.isNotEmpty(fileId)){
            String newFileId = StringUtils.strip(fileId,"[]");
            String[] fileIds = newFileId.split(",");
            for(int i = 0 ;i < fileIds.length; i++){
                //判断fileId是否已经存在
                File file = fileMapper.selectFileById(Integer.parseInt(fileIds[i]));
                if(file != null){
                    setMessageFileId(message.getId(),Integer.parseInt(fileIds[i]));
                }
            }
        }
        return messageMapper.updateMessage(message);
    }

    /**
     * 删除留言对象
     *
     * @param id 留言ID
     * @return 结果
     */
    @Override
    public int deleteMessageById(Long id)
    {
        return messageMapper.deleteMessageById(id);
    }

    /**
     * 批量删除留言信息
     *
     * @param ids 需要删除的留言ID
     * @return 结果
     */
    @Override
    public int deleteMessageByIds(Long[] ids)
    {
        return messageMapper.deleteMessageByIds(ids);
    }

    @Override
    public int endMessageById(Long id) {
        return messageMapper.endMessageById(id);
    }

    @Override
    public Map countMessage() {
        /**处理状态：1处理中(messageStatus = 1 或者 2)，2已处理(messageStatus = 3)*/
        Integer totalNum = 0;
        AtomicInteger dealedNum = new AtomicInteger(0); // 初始化为0
        AtomicInteger dealingNum = new AtomicInteger(0); // 初始化为0

        Map returnMap = new HashMap();
        List<Map> list = messageMapper.countMessage();
        if(CollectionUtil.isNotEmpty(list)){
            list.stream().forEach(map -> {
                if(map != null && map.get("messageStatus") != null){
                    Integer messageStatus = Integer.parseInt(map.get("messageStatus").toString());
                    Integer num = Integer.parseInt(map.get("num").toString());
                    if(messageStatus == 1){ //处理中
                        dealingNum.getAndAdd(num);
                    }else { // 已处理
                        dealedNum.getAndAdd(num);
                    }
                }
            });
            totalNum = dealingNum.get() + dealedNum.get();

        }

        returnMap.put("totalNum",totalNum);
        returnMap.put("dealingNum",dealingNum);
        returnMap.put("dealedNum",dealedNum);
        return returnMap;
    }

    @Override
    public void replyMessage(SysReply reply) throws ClientException {
        /*
          回复完用户的留言后，需要发送邮件或者短信通知用户
          短信模板：【亿康基因】 亲爱的Xxx您好，您的Xxx留言已回复，请您登陆系统进行查阅。
          1、发送短信或者邮件
          2、先获取当前登录用户的userId，然后获取userId的信息
          3、判断当前登录用户是否为注册用户，如果是则继续判断是哪种注册类型，
             如果是手机注册，则先发送短信，没有手机则发送邮件。如果是邮件注册，则相反
        */
        //首先获取reply中的messageId
        Long messageId = reply.getMessageId();
        //根据messageId，找到对应的信息
        SysMessage sysMessage = messageMapper.selectMessageById(messageId);
        if(sysMessage != null){
           String messageTitle = sysMessage.getMessageTitle();
           //获取创建人id
            String createBy = sysMessage.getCreateBy();
            //根据createBy找到对应的用户
            SysUser sysUser = sysUserMapper.selectUserById(Long.parseLong(createBy));

            String name = "";
            String content = messageTitle;
            if(sysUser != null){
                name = sysUser.getNickName();
            }

            //判断sysUser的注册类型，手机注册发手机， 邮箱注册发邮箱
            String isRegister = sysUser.getIsRegister();
            String registerType = sysUser.getRegisterType();
            if(StringUtils.isNotEmpty(isRegister)&&isRegister.equals("1") //手机
                    &&StringUtils.isNotEmpty(registerType)&&registerType.equals("1")){
            String phonenumber = sysUser.getPhonenumber();
                if(StringUtils.isNotEmpty(phonenumber)){
                        //发送手机
                    JSONObject obj = new JSONObject();
                    obj.put("name", name);
                    obj.put("content", content);
                    messageUtil.sendSms(phonenumber, "SMS_462300067", obj);
                }
            }else if(StringUtils.isNotEmpty(isRegister)&&isRegister.equals("1") //邮箱
                    &&StringUtils.isNotEmpty(registerType)&&registerType.equals("2")){
                    String email = sysUser.getEmail();
                    Map valueMap = new HashMap();
                    valueMap.put("to",email);
                    valueMap.put("title","尊敬的用户" + sysUser.getNickName());
                    valueMap.put("content","【亿康基因】" + "亲爱的" + name + "您好，您的" + content + "留言已回复，请您登陆系统进行查阅。" );
                    String thymeleaf="";
                emailUtils.sendMail(valueMap,thymeleaf);
            }
        }

    }


    //将message的信息与文件信息绑定
    private void setMessageFileId(Long id,Integer fileId){
        File file = new File();
        file.setMessageId(id);
        file.setId(fileId);
        fileMapper.updateFile(file);
    }

    private List<SysUser> getCEOList(String roleName){
        SysRole sysRole = new SysRole();
        sysRole.setDelFlag("0");
        sysRole.setStatus("0");
        sysRole.setRoleName(roleName);
        List<SysUser> userList = sysUserMapper.getCEOListByRoleName(roleName);
        return userList;
    }
}
